import { api } from "@/global/utils/api"
import useApiPromiseHandler from "./api-promise-handler"
import { useI18n } from "vue-i18n" 
import { ref, watch } from 'vue';
import useStaff from "./staff";

export default function useFindPosts() {
  const { getLocalStaff } = useStaff();
  const { t } = useI18n();
  const departmentOnly = ref(true);
  const currentPage = ref(1);
  const PAGESIZE = 5;
  const isFetchingList = ref(false);
  const postList = ref([]);
  const noMore = ref(false);

  watch(departmentOnly, (v, oldV) => {
    // 如果正在 fetching， 不允许改变这个行为
    if (isFetchingList.value) {
      departmentOnly.value = oldV;
      return;
    }
    console.log(v);
    noMore.value = false;
    postList.value = [];
    currentPage.value = 1;
    fetch();
  })

  const findPosts = (page, countPerPage, departmentId, onSuccessed, onFaild) => {
    const url = departmentId == null ? `/posts/findAll/${page}/${countPerPage}` : `/posts/findAll/${page}/${countPerPage}/${departmentId}`;
    useApiPromiseHandler(t,
      api.get(url),
      onSuccessed, onFaild,
      () => isFetchingList.value = false
    )
  };

  const fetch = () => {
    if (noMore.value) return;
    isFetchingList.value = true;
    const departmentId = departmentOnly.value ? getLocalStaff().department.id : null;
    findPosts(currentPage.value, PAGESIZE, departmentId, (resp) => {
      resp.data.content.forEach(post => {
        post.resources = post.resources.map(originalUrl => {
          return {
            url: originalUrl,
            previewUrl: `${originalUrl}?imageMogr2/thumbnail/400x`
          }
        });
        postList.value.push(post);
      });
      if (!resp.data.last)
        currentPage.value++;
      else 
        noMore.value = true;
    }, (err) => console.log(err));
  };


  return { fetch, departmentOnly, currentPage, isFetchingList, postList, noMore };
}